package cn.lee.chp1;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import cn.lee.TomcatConstants;

/**
 * HTTP response - status-Line
 * ((general-header|response-header|entity-header)CRLF)
 * CRLF
 * [message-body]
 * status-line=HTTP-Version SP Status-Code SP Reason-Phrase CRLF
 * @author huaigang
 *
 */
public class Response {
    OutputStream output;
    Request request;
    public static final int BUFFER_SIZE = 2048;
    public Response(OutputStream output) {
        this.output = output;
    }
    
    public void setRequest(Request request){
        this.request = request;
    }
    public void sendStaticResource() throws IOException{
        String uri = request.getUri();
        File file = new File(HttpServer.WEB_ROOT, uri);
        if(!file.exists()){
            file = new File(HttpServer.WEB_ROOT, TomcatConstants.URL_404);
        }
        InputStream is = null;
        try{
            is = new FileInputStream(file);
            byte[] b = new byte[BUFFER_SIZE];
            int rsize = 0;
            while((rsize = is.read(b)) != -1){
                output.write(b, 0, rsize);
            }
        }finally{
            is.close();
        }
    }
}
